<?php
session_start();

// 设置验证码图片的宽度和高度
$width = 100;
$height = 40;

// 创建图像资源
$image = imagecreatetruecolor($width, $height);

// 设置背景色
$bg_color = imagecolorallocate($image, 243, 251, 254);
imagefill($image, 0, 0, $bg_color);

// 添加干扰线
for ($i = 0; $i < 6; $i++) {
    $line_color = imagecolorallocate($image, mt_rand(150, 220), mt_rand(150, 220), mt_rand(150, 220));
    imageline($image, mt_rand(0, $width), mt_rand(0, $height), mt_rand(0, $width), mt_rand(0, $height), $line_color);
}

// 添加干扰点
for ($i = 0; $i < 100; $i++) {
    $pixel_color = imagecolorallocate($image, mt_rand(150, 220), mt_rand(150, 220), mt_rand(150, 220));
    imagesetpixel($image, mt_rand(0, $width), mt_rand(0, $height), $pixel_color);
}

// 生成随机验证码
$captcha_code = '';
$chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$length = strlen($chars) - 1;

for ($i = 0; $i < 4; $i++) {
    $captcha_code .= $chars[mt_rand(0, $length)];
}

// 将验证码保存到会话
$_SESSION['captcha'] = strtolower($captcha_code);

// 在图像上绘制验证码
$text_color = imagecolorallocate($image, 33, 150, 243);

// 不使用TTF字体，改用内置字体
$font = 5; // 使用内置字体5
$x = 10;
$y = 20;

for ($i = 0; $i < strlen($captcha_code); $i++) {
    $char = $captcha_code[$i];
    imagechar($image, $font, $x + $i * 20, $y, $char, $text_color);
}

// 输出图像
header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);
?> 